package com.datasecops.scannerservices.util;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HttpURL连接工具类
 *
 * @author: SunLingzhi
 * @time: 2022/8/17 17:07
 */
@Component
@Slf4j
public class HttpURLHelper {

    /**
     * 开始连接
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/17 17:10
     */
    public static String connection(String url,byte[] paramData) {
        HttpURLConnection connection = null;
        try {
            byte[] b = new byte[]{};
            URL restUrl = new URL(url);//读取初始URL，并且创建数据
            connection = (HttpURLConnection) restUrl.openConnection();//打开url连接
            connection.setRequestProperty("Content-type", "application/x-java-serialized-object"); //设置请求参数  可以指定接收json参数  服务端的key为content-type
            connection.setRequestMethod("POST");
            //设置主机连接超时(单位：毫秒)
            // 发送请求端 连接到 url目标地址端的时间   受距离长短和网络速度的影响
            connection.setConnectTimeout(5000);
            connection.setDoOutput(true);// 设置是否向 HttpUrlConnection 输出，对于post请求，参数要放在 http 正文内，因此需要设为true，默认为false。
            connection.setDoInput(true);// 设置是否从 HttpUrlConnection读入，默认为true
            connection.setUseCaches(false);// 设置是否使用缓存
            connection.connect();// 连接

            // 写入参数到请求中
            OutputStream out = connection.getOutputStream();
            out.write(paramData);
            out.flush();
            out.close();

            int code = connection.getResponseCode();
            if (200 == code) {
                InputStream is = connection.getInputStream();
                byte[] retStream = ByteStreamHelper.inputStreamTOByte(is);
                if (retStream.length < 9) {
                    log.error("HttpURLHelper retStream length too short:" + retStream.length);
                    return null;
                }
                byte successByte = retStream[2];//成功标志位
                String info = ByteStreamHelper.getFailureDetails(retStream);
                if (successByte == 0x01) {//成功
                    log.info("HttpURLHelper return succeeded");
                    //查看返回数据
                    return info;
                } else {
                    log.info("HttpURLHelper return failed info:" + info + " &url: " + url);
                }
            } else {
                log.info("HttpURLHelper return failed code:" + code + " &url: " + url);
            }
        } catch (Exception e) {
            log.error("Failed method HttpURLHelper url: " + url + " &error:" + e.getMessage());
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        Element rootNode = DocumentHelper.createElement("Parameters");//:创建文档并设置文档的根元素节点

        byte[] paramData = null;
        try {
            String strParamXml = ByteStreamHelper.toXmlString(rootNode);
            paramData = ByteStreamHelper.formatParamDataFlow(strParamXml);
        } catch (IOException e) {
            e.printStackTrace();
        }


        String url = "http://10.26.18.62:3311/EE/DlpSrvInfoToClient?Type=DlpSystemConfig";
        HttpURLHelper.connection(url,paramData);
    }
}
